<template>
  <el-dialog
    v-model="dialogVisible"
    title="角色详情"
    width="800px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <div v-if="role" class="role-detail">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><InfoFilled /></el-icon>
          基本信息
        </h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色名称">
            <div class="role-name-detail">
              <span>{{ role.name }}</span>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="角色编码">
            <el-tag v-if="role.code" type="info" class="code-tag">{{ role.code }}</el-tag>
            <span v-else class="empty-code">暂无编码</span>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="role.status ? 'success' : 'danger'">
              {{ role.status ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户数量">
            <el-tag type="primary">{{ role.userCount || 0 }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(role.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            <span class="description">{{ role.description || '暂无描述' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 权限信息 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><Key /></el-icon>
          权限信息
          <el-button 
            type="primary" 
            size="small" 
            @click="handleEditPermissions"
            v-if="userStore.hasPermission('role.assign')"
          >
            编辑权限
          </el-button>
          <span v-if="permissions.length === 0" class="permissions-count-zero">(0)</span>
        </h3>
        <div v-loading="permissionLoading" class="permissions-content">
          <div v-if="permissions.length === 0" class="empty-permissions">
            <el-empty description="暂无权限配置" />
          </div>
          <div v-else class="permission-groups">
            <div 
              v-for="group in permissionGroups" 
              :key="group.name" 
              class="permission-group"
            >
              <div class="group-header">
                <el-icon><Component :is="getModuleIcon(group.name)" /></el-icon>
                <span class="group-name">{{ group.name }}</span>
                <el-tag size="small" type="info">{{ group.permissions.length }}</el-tag>
              </div>
              <div class="group-permissions">
                <el-tag 
                  v-for="permission in group.permissions" 
                  :key="permission.id"
                  class="permission-tag"
                  size="small"
                >
                  {{ permission.name }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><User /></el-icon>
          关联用户
          <el-link v-if="role.userCount > 0" type="primary" @click="viewAllUsers">查看全部</el-link>
          <span v-else class="user-count-zero">(0)</span>
        </h3>
        <div v-loading="usersLoading" class="users-content">
          <div v-if="!users.length" class="empty-users">
            <el-empty description="暂无关联用户" />
          </div>
          <div v-else class="user-list">
            <div 
              v-for="user in users" 
              :key="user.id" 
              class="user-item"
            >
              <el-avatar :size="36" class="user-avatar">
                {{ user.username?.[0]?.toUpperCase() || 'U' }}
              </el-avatar>
              <div class="user-info">
                <div class="user-name">{{ user.username }}</div>
                <div class="user-email">{{ user.email }}</div>
              </div>
              <el-tag 
                :type="user.status ? 'success' : 'danger'" 
                size="small"
                class="status-tag"
              >
                {{ user.status ? '正常' : '禁用' }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作历史 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><Clock /></el-icon>
          操作历史
        </h3>
        <div v-loading="historyLoading" class="history-content">
          <el-timeline>
            <el-timeline-item
              v-for="item in operationHistory"
              :key="item.id"
              :timestamp="item.createdAt"
              :type="getTimelineType(item.action)"
            >
              <div class="history-item">
                <div class="history-action">{{ item.action }}</div>
                <div class="history-details">{{ item.details }}</div>
                <div class="history-user">操作人：{{ item.operator }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleEdit"
          v-if="userStore.hasPermission('role.update')"
        >
          编辑角色
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { InfoFilled, Key, Menu, User, Clock, UserFilled, Setting, Lock, Document } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userApi } from '@/api/user'
import { roleApi } from '@/api/role'
import { formatDate } from '@/utils'

const props = defineProps({
  visible: Boolean,
  role: Object
})

const emit = defineEmits(['update:visible', 'edit', 'edit-permissions'])

const userStore = useUserStore()

const permissionLoading = ref(false)
const usersLoading = ref(false)
const historyLoading = ref(false)
const permissions = ref([])
const users = ref([])
const operationHistory = ref([])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 权限分组
const permissionGroups = computed(() => {
  // 定义模块排序顺序
  const moduleOrder = {
    '用户管理': 1,
    '角色管理': 2,
    '权限管理': 3,
    '系统设置': 4,
    '日志管理': 5,
    '其他': 99
  }

  const groups = {}
  permissions.value.forEach(permission => {
    const groupName = permission.module || '其他'
    if (!groups[groupName]) {
      groups[groupName] = {
        name: groupName,
        permissions: [],
        order: moduleOrder[groupName] || 50 // 使用预定义的顺序或默认值
      }
    }
    groups[groupName].permissions.push(permission)
  })
  
  // 按模块排序返回分组数组
  return Object.values(groups).sort((a, b) => a.order - b.order)
})

// 监听角色变化，加载详细数据
watch(() => props.role, (newRole) => {
  if (newRole && props.visible) {
    loadRoleDetails()
  }
}, { immediate: true })

const loadRoleDetails = async () => {
  if (!props.role) return
  
  await Promise.all([
    loadRolePermissions(),
    loadRoleUsers(),
    loadOperationHistory()
  ])
}

const loadRolePermissions = async () => {
  try {
    permissionLoading.value = true
    
    // 使用API获取角色权限
    const response = await roleApi.getRolePermissions(props.role.id)
    
    if (response && response.code === 200 && response.data) {
      // 处理API返回的权限数据
      permissions.value = response.data.map(permission => ({
        id: permission.id,
        name: permission.name || permission.permissionName,
        code: permission.code || permission.permissionCode,
        module: permission.module || permission.moduleName || '其他'
      }))
    } else {
      // 如果API调用失败或返回数据格式不正确，使用备用数据
      console.warn('加载权限数据格式不正确，使用备用数据')
      permissions.value = [
        { id: 1, name: '查看用户', code: 'user.view', module: '用户管理' },
        { id: 2, name: '创建用户', code: 'user.create', module: '用户管理' },
        { id: 4, name: '查看角色', code: 'role.view', module: '角色管理' },
        { id: 6, name: '系统配置', code: 'system.config', module: '系统设置' }
      ]
    }
  } catch (error) {
    console.error('加载权限失败:', error)
    // 错误时使用空数组
    permissions.value = []
  } finally {
    permissionLoading.value = false
  }
}

const loadRoleUsers = async () => {
  try {
    usersLoading.value = true
    
    // 根据角色的userCount确定要显示的用户数量
    const maxUsers = props.role.userCount || 0
    
    // 仅当有关联用户时才调用API
    if (maxUsers > 0) {
      // 使用userApi获取角色关联用户，限制显示与userCount一致的数量
      const response = await userApi.getUsers({
        roleId: props.role.id,
        pageSize: maxUsers
      })
      
      if (response && response.code === 200 && response.data) {
        // 处理API返回的用户数据，确保数量不超过角色的userCount
        users.value = response.data.map(user => ({
          id: user.id,
          username: user.username || user.userName,
          email: user.email,
          avatar: user.avatar,
          status: user.isActive ? 1 : 0
        })).slice(0, maxUsers)
      } else {
        // 如果API调用失败或数据格式不正确，使用模拟数据作为备选
        console.warn('加载用户数据格式不正确，使用备用数据')
        users.value = [
          {
            id: 1,
            username: 'admin',
            email: 'admin@example.com',
            avatar: '',
            status: 1
          },
          {
            id: 2,
            username: 'user001',
            email: 'user001@example.com',
            avatar: '',
            status: 1
          },
          {
            id: 3,
            username: 'user002',
            email: 'user002@example.com',
            avatar: '',
            status: 0
          }
        ].slice(0, maxUsers)
      }
    } else {
      // 如果角色没有关联用户，则清空用户列表
      users.value = []
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    // 发生错误时使用模拟数据
    users.value = [
      {
        id: 1,
        username: 'admin',
        email: 'admin@example.com',
        avatar: '',
        status: 1
      }
    ].slice(0, 1)
  } finally {
    usersLoading.value = false
  }
}

const loadOperationHistory = async () => {
  try {
    historyLoading.value = true
    
    // 模拟加载操作历史
    await new Promise(resolve => setTimeout(resolve, 400))
    
    operationHistory.value = [
      {
        id: 1,
        action: '角色创建',
        details: `创建了角色 "${props.role.name}"`,
        operator: 'admin',
        createdAt: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        action: '权限更新',
        details: '更新了角色权限配置',
        operator: 'admin',
        createdAt: '2024-01-20 14:20:00'
      },
      {
        id: 3,
        action: '用户分配',
        details: '分配给用户 user001',
        operator: 'admin',
        createdAt: '2024-01-25 09:15:00'
      }
    ]
  } catch (error) {
    console.error('加载操作历史失败:', error)
  } finally {
    historyLoading.value = false
  }
}

const getTimelineType = (action) => {
  switch (action) {
    case '角色创建':
      return 'success'
    case '权限更新':
      return 'primary'
    case '用户分配':
      return 'info'
    case '角色删除':
      return 'danger'
    default:
      return 'primary'
  }
}

const handleEdit = () => {
  emit('edit', props.role)
  dialogVisible.value = false
}

const handleEditPermissions = () => {
  // 将当前角色和权限传递给父组件
  emit('edit-permissions', {
    role: props.role,
    currentPermissions: permissions.value.map(p => p.id)
  })
  
  // 编辑完成后需要重新加载权限
  ElMessage.success('权限编辑功能已激活')
}

const router = useRouter()

const viewAllUsers = () => {
  // 跳转到用户管理页面并传递角色ID作为查询参数
  router.push({
    path: '/home/users',
    query: { roleId: props.role.id, roleName: props.role.name }
  })
  // 关闭当前详情对话框
  dialogVisible.value = false
}

// 根据模块名称获取对应的图标
const getModuleIcon = (moduleName) => {
  switch (moduleName.toLowerCase()) {
    case '用户管理':
      return 'User'
    case '角色管理':
      return 'UserFilled'
    case '系统设置':
      return 'Setting'
    case '权限管理':
      return 'Lock'
    case '日志管理':
      return 'Document'
    default:
      return 'Menu'
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleClosed = () => {
  permissions.value = []
  users.value = []
  operationHistory.value = []
}
</script>

<style scoped>
.role-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 32px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  border-bottom: 2px solid #e5e7eb;
  padding-bottom: 8px;
}

.role-name-detail {
  display: flex;
  align-items: center;
  gap: 8px;
}

.code-tag {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.description {
  color: #6b7280;
  line-height: 1.5;
}

.permissions-content {
  min-height: 100px;
}

.empty-permissions {
  text-align: center;
  padding: 40px 0;
}

.permission-groups {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.permission-group {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.group-name {
  font-weight: 500;
  color: #374151;
  flex: 1;
}

.group-permissions {
  padding: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  background: #f0f9ff;
  border-color: #0ea5e9;
  color: #0c4a6e;
}

.users-content {
  min-height: 120px;
}

.empty-users {
  text-align: center;
  padding: 20px 0;
  color: #9ca3af;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #f9fafb;
  transition: all 0.2s ease;
}

.user-item:hover {
  border-color: #d1d5db;
  background: #f3f4f6;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.user-avatar {
  background: #60a5fa;
  color: white;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #1f2937;
  line-height: 1.2;
  font-size: 14px;
}

.user-email {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.2;
  margin-top: 2px;
}

.status-tag {
  min-width: 48px;
  text-align: center;
}

.user-count-zero,
.permissions-count-zero {
  color: #9ca3af;
  font-size: 12px;
  margin-left: 8px;
  font-weight: normal;
}

.history-content {
  min-height: 150px;
}

.history-item {
  padding: 8px 0;
}

.history-action {
  font-weight: 500;
  color: #374151;
  margin-bottom: 4px;
}

.empty-code {
  color: #9ca3af;
  font-style: italic;
}

.history-details {
  color: #6b7280;
  font-size: 14px;
  margin-bottom: 4px;
}

.history-user {
  color: #9ca3af;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条样式 */
.role-detail::-webkit-scrollbar {
  width: 6px;
}

.role-detail::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.role-detail::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.role-detail::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 描述样式 */
:deep(.el-descriptions__body) {
  background: #fafafa;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #374151;
  background: #f3f4f6 !important;
}

:deep(.el-descriptions__content) {
  color: #6b7280;
}

/* 时间线样式 */
:deep(.el-timeline-item__timestamp) {
  color: #9ca3af;
  font-size: 12px;
}

:deep(.el-timeline-item__content) {
  padding-left: 16px;
}
</style>
